package com.example.myproject.service.serviceImpl;


import com.example.myproject.model.Role;
import com.example.myproject.repository.RoleRepository;
import com.example.myproject.service.FunctionService;
import com.example.myproject.service.RoleService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

@Service
public class RoleServiceImpl implements RoleService {
    private static final Logger logger = LoggerFactory.getLogger(RoleServiceImpl.class);


    @Autowired
    private RoleRepository roleRepository;
    @Autowired
    private FunctionService functionService;
    @Override
    public Role createRole(Role role){
        logger.debug("正在创建角色，角色详情：{}", role);
        Role savedRole = roleRepository.save(role);
        logger.info("角色创建成功，角色ID：{}", savedRole.getId());
        return savedRole;
    }

    @Override
    public List<Role> getAllRoles() {
        logger.debug("正在获取所有角色");
        List<Role> roles = roleRepository.findAll();
        logger.info("已获取角色总数：{}", roles.size());
        return roles;
    }

    @Override
    public Role updateRole(String name, Role roleDetails) {
        logger.debug("正在更新角色，原角色名：{}", name);
        Optional<Role> optionalRole = Optional.ofNullable(roleRepository.findByName(name));
        if (optionalRole.isPresent()) {
            Role role = optionalRole.get();
            logger.info("找到角色，正在更新，角色ID：{}", role.getId());
            role.setName(roleDetails.getName());
            role.setDescription(roleDetails.getDescription());
            role.setStatus(roleDetails.getStatus());

            String functionIds = roleDetails.getFunctions();

            role.setFunctions(functionIds);
            Role updatedRole = roleRepository.save(role);
            logger.info("角色更新成功，更新后的角色详情：{}", updatedRole);
            return updatedRole;
        } else {
            logger.warn("未找到名称为 '{}' 的角色，更新失败", name);
            return null;
        }
    }
    @Override
    public List<Role> searchRolesByName(String name) {
        logger.debug("正在搜索角色，搜索词：{}", name);
        List<Role> roles = roleRepository.findBynameContaining(name);
        logger.info("搜索到的角色数量：{}", roles.size());
        return roles;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteRole(String name) {
        logger.debug("正在删除角色，角色名：{}", name);
        roleRepository.deleteByName(name);
        logger.info("角色名为 '{}' 的角色已被删除", name);
    }
}
